

package com.xgit.iov.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xgit.iov.admin.mapper.SysDataRuleMapper;
import com.xgit.iov.admin.mapper.SysRoleDataRuleMapper;
import com.xgit.iov.admin.service.SysDataRuleService;
import com.xgit.iov.common.core.constant.CacheConstants;
import com.xgit.iov.common.core.entity.IovUser;
import com.xgit.iov.common.core.entity.SysDataRule;
import com.xgit.iov.common.core.entity.SysRoleDataRule;
import com.xgit.iov.common.core.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 数据权限类
 * </p>
 *
 * @author william
 * @since 2020/5/28
 */
@Service
@RequiredArgsConstructor
public class SysDataRuleServiceImpl extends ServiceImpl<SysDataRuleMapper, SysDataRule> implements SysDataRuleService {

	private final SysRoleDataRuleMapper sysRoleDataRuleMapper;

	/**
	 * 通过用户ID，查询角色信息
	 * @param userId
	 * @return
	 */
	@Override
	public List findByUserId(Long userId) {
		return baseMapper.findByUserId(userId);
	}

	/**
	 * 通过数据权限ID，删除角色关系,并清空角色数据权限缓存
	 *
	 * @param id
	 * @return
	 */
	@Override
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeDataRuleById(Long id) {
		sysRoleDataRuleMapper.delete(Wrappers
			.<SysRoleDataRule>update().lambda()
			.eq(SysRoleDataRule::getRoleId, id));
		return this.removeById(id);
	}

	@Override
	public List<SysDataRule> getDataRule() {
		List<SysDataRule> dataRuleList;
		IovUser user = SecurityUtils.getUser();
		if (user.isAdmin()){
			dataRuleList = Lists.newArrayList();
		}else{
			dataRuleList = baseMapper.findByUserId(user.getId());
		}
		return dataRuleList;
	}


}
